﻿
using System.Data.Entity;
using Qi.Data.Contracts;

namespace Qi.Data.EntityFramework
{
    using System;
    
    public class EntityFrameworkUnitOfWork<TContext> : IUnitOfWork 
        where TContext : DbContext, new()
    {
        public EntityFrameworkUnitOfWork()
        {
            this.DbContext = new TContext();
            ConfigureContext(this.DbContext);
        }

        protected virtual void ConfigureContext(TContext dbContext)
        {
            dbContext.Configuration.ProxyCreationEnabled = false;
            dbContext.Configuration.LazyLoadingEnabled = false;
            dbContext.Configuration.ValidateOnSaveEnabled = false;
        }

        protected TContext DbContext { get; private set; }

        public void Commit()
        {
            this.DbContext.SaveChanges();           
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (this.DbContext == null)
            {
                return;
            }

            this.DbContext.Dispose();
            this.DbContext = null;
        }
    }
}